package com.zmn.oms.third.taobao;

import com.alibaba.fastjson.JSON;
import com.zmn.base.common.data.common.dro.tags.TagsDRO;
import com.zmn.oms.manager.utils.SpringBeanFactoryUtil;
import com.zmn.oms.third.taobao.dto.TaobaoAccessToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @date 2019/06/13 16:54
 */
public class TaobaoTokenManager {
    private static final Logger logger = LoggerFactory.getLogger(TaobaoTokenManager.class);

    public static String TOKEN;// = "6201905d630d0ZZ7c9896520a671383962985ad41f9dd822563261712";

    public static String getToken() {
        if (StringUtils.isNotBlank(TOKEN)) {
            return TOKEN;
        }

        TaobaoAccessTokenService taobaoAccessTokenService = SpringBeanFactoryUtil.getBean("taobaoAccessTokenService");
        TagsDRO baseCodeMapDRO = taobaoAccessTokenService.queryToken();
        if (baseCodeMapDRO != null) {
            TaobaoAccessToken token = JSON.parseObject(baseCodeMapDRO.getName(), TaobaoAccessToken.class);
            TOKEN = token.getAccessToken();
            logger.info("【{}】<queryAccessToken> TaobaoAccessToken:[{}]", TaobaoTmcConstants.NAME_TMALL, token.toString());
        } else {
            logger.info("【{}】<queryAccessToken> 查找失败。", TaobaoTmcConstants.NAME_TMALL);
        }
        return TOKEN;
    }

    public synchronized static void setToken(TaobaoAccessToken token) {
        TaobaoAccessTokenService taobaoAccessTokenService = SpringBeanFactoryUtil.getBean("taobaoAccessTokenService");

        if (token != null && StringUtils.isNotBlank(token.getAccessToken())) {
            TOKEN = token.getAccessToken();
        }

        boolean isSuccess = false;
        try {
            isSuccess = taobaoAccessTokenService.saveToken(token);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (isSuccess) {
            logger.info("【{}】<saveAccessToken> 保存成功。", TaobaoTmcConstants.NAME_TMALL);
        } else {
            logger.info("【{}】<saveAccessToken> 保存失败。", TaobaoTmcConstants.NAME_TMALL);
        }
    }

}

